﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace PhotoGallery.Infrastructure.Helpers
{
    public static class ModelBinderHelper
    {
        public static T FromPostedData<T>(ModelBindingContext context, string key)
        {
            return FromPostedData<T>(context, key, true);
        }

        public static T FromPostedData<T>(ModelBindingContext context, string key, bool stripHtml)
        {
            ValueProviderResult result;
            result = context.ValueProvider.GetValue(key);

            context.ModelState.SetModelValue(key, result);

            if (result != null)
            {
                var r = (T)result.ConvertTo(typeof(T));

                if (stripHtml && typeof(T) == typeof(String))
                {
                    return (T)((object)StringHelper.StripHtml(r.ToString()).Trim());
                }

                return r;
            }
            else
            {
                return default(T);
            }
        }
    }
}
